<template>
  <div>
    <Table class="friends-list" :columns="columns1" :data="friendsList" @on-row-click="startDiaglog"
           width="200" ref="table"></Table>
    <div v-if="dialogObj!=null" class="dialog-box">
      <div class="dialog-title">
        <div class="dialog-title-content">正在与 {{dialogObj.fName}} 对话</div>
      </div>
      <div class="dialog-content">
        <div v-for="dialog in  dialogList">
          <div v-if="dialog.mFromUserID ==userId " class="dialog-msg-me right">
            {{dialog.mPostMessages}}
          </div>
          <div v-else class="dialog-msg-other">
            {{dialog.mFromUserID}}:{{dialog.mPostMessages}}
          </div>
        </div>

      </div>
      <div class="dialog-input">
        <Input @on-enter="webSocketSend" v-model="inputText" type="textarea" :rows="4"
               placeholder="Enter something..."></Input>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        columns1: [
          {
            title: '好友编号',
            key: 'fFriendId'
          },
          {
            title: '昵称',
            key: 'fName'
          }
        ],
        userId: this.$store.state.user.id,
        friendsList: [],
        inputText: '',
        dialogList: [],
        dialogObj: null,
        websock: undefined
      }
    },
    created () {
      this.getUserInfo()
      // 打开一个 web socket
      this.initWebSocket()
    },
    methods: {
      startDiaglog (data) {
        this.dialogObj = data
        this.getMessages(this.userId, data.fFriendId)
      },
      getMessages (mFromUserID, mToUserID) {
        let self = this
        this.$http({
          url: this.$http.adornUrl('/im/messages/list'),
          method: 'post',
          params: {
            'mFromUserID': mFromUserID,
            'mToUserID': mToUserID
          }
        }).then(({data}) => {
          if (data && data.code === 0) {
            self.dialogList = data.data
          }
        })
      },
      // 获取当前管理员信息
      getUserInfo () {
        let self = this
        this.$http({
          url: this.$http.adornUrl('/im/friends/list'),
          method: 'post',
          params: {
            'userId': this.$store.state.user.id
          }
        }).then(({data}) => {
          if (data && data.code === 0) {
            self.friendsList = data.data
          }
        })
      },
      initWebSocket () { // 初始化weosocket
        const wsUrl = 'ws://127.0.0.1:6789'// ws地址
        this.websock = new WebSocket(wsUrl)
        this.websock.onopen = this.webSocketOnOpen

        this.websock.onerror = this.webSocketOnError

        this.websock.onmessage = this.webSocketOnMessage
        this.websock.onclose = this.webSocketClose
        console.log(this.websock)
      },
      webSocketOnOpen () {
        console.log('WebSocket连接成功')
      },
      webSocketOnError (e) { // 错误
        console.log('WebSocket连接发生错误')
      },
      webSocketOnMessage (e) { // 数据接收
        const redata = JSON.parse(e.data)
        // 注意：长连接我们是后台直接1秒推送一条数据，
        // 但是点击某个列表时，会发送给后台一个标识，后台根据此标识返回相对应的数据，
        // 这个时候数据就只能从一个出口出，所以让后台加了一个键，例如键为1时，是每隔1秒推送的数据，为2时是发送标识后再推送的数据，以作区分
        console.log(redata.value)
      },
      webSocketSend () { // 数据发送
        let msg = {
          'mFromUserID': this.$store.state.user.id,
          'mToUserID': this.dialogObj.fId,
          'mPostMessages': this.inputText
        }
        this.dialogList.push(msg)
        /*
         M_ID bigint  NOT NULL AUTO_INCREMENT,
         M_PostMessages Text NOT NULL COMMENT '消息内容',
         M_Time DATETIME NOT NULL COMMENT '发送时间',
         M_status bit COMMENT '接收状态',
         M_FromUserID BIGINT NOT NULL COMMENT '发送者id',
         M_ToUserID BIGINT NOT NULL COMMENT '接收者id',
         */
        this.websock.send(JSON.stringify(msg))
        this.inputText = ''
      },
      webSocketClose (e) { // 关闭
        console.log('connection closed (' + e.code + ')')
      }

    }
  }
</script>

<style type="text/css" scoped>
  .ivu-input-wrapper {
    display: block;
  }

  /*.dialog-msg-me {*/
  /*float: right;*/
  /*}*/

  .right {
    text-align: right;
    width: 290px;
    background-color: #b0e0e6;
  }

  .dialog-box, .friends-list {
    display: inline-block;
    margin-top: 2px;
    background-color: #0BB2D4;
    width: 300px;
    height: 500px;
  }

  .dialog-title-content {
    /*position: absolute;*/
    border: 1px solid #000;
    width: 100%;
    height: 100%;
    top: -50%;
    left: -50%;
  }

  .dialog-title {
    width: 100%;
    height: 10%;
    /*top:-50%;*/
    /*line-height: 10%;*/
    /*text-align: center;*/
    background-color: #80848f;
  }

  .dialog-content {
    width: 100%;
    height: 70%;
    border: 1px solid grey;
    background-color: white;
  }

  .dialog-input {
    width: 100%;
    height: 20%;
    margin-bottom: 0;
    /*border: 1px solid grey;*/
    background-color: white;
  }
</style>

